var util = require('../../libs/util.js');
//获取应用实例
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    loading_time: '00:00',
    reach_distance_limit: 0,
    is_custom_distance:false,
    price_driver_show:true,
    shop_time_fromwh:false,
    driver_operation_exception_warn:false,
    no_vehicle_warn_time:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    if (e.id) {
      this.setData({
        id: e.id
      })
    }
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  switchChange(e) {
    console.log(e)
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  loadData: function () {
    var that = this;
  },
  backToList: function () {
    wx.redirectTo({
      url: '/pages/enterprise/warehouse'
    })
  },
  setRouterConfig: function () {
    if (this.data.coord == '' || this.data.coord == undefined) {
      wx.showToast({
        title: "没有发货点坐标",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var dataList = this.data.dataList;
    wx.navigateTo({
      url: '/pages/schedule/apps/router_config?coord=' + this.data.coord
    })
  },
  formSubmit: function () {
    var that = this;
    var dataList = that.data.dataList;
    var tp_threshold_max = that.data.tp_threshold_max;
    var tp_threshold_min = that.data.tp_threshold_min;
    if (isNaN(tp_threshold_max) == true) {
      tp_threshold_max = '';
    }
    if (isNaN(tp_threshold_min) == true) {
      tp_threshold_min = '';
    }
    if ((tp_threshold_max == '' && tp_threshold_min != '') || (tp_threshold_max != '' && tp_threshold_min == '')) {
      wx.showToast({
        title: "温度阈值缺少",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (tp_threshold_max != '' && tp_threshold_min != '' && tp_threshold_max <= tp_threshold_min) {
      wx.showToast({
        title: "温度阈值不合法",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var hr_threshold_max = that.data.hr_threshold_max;
    var hr_threshold_min = that.data.hr_threshold_min;
    if (isNaN(hr_threshold_max) == true) {
      hr_threshold_max = '';
    }
    if (isNaN(hr_threshold_min) == true) {
      hr_threshold_min = '';
    }
    if ((hr_threshold_max == '' && hr_threshold_min != '') || (hr_threshold_max != '' && hr_threshold_min == '')) {
      wx.showToast({
        title: "湿度阈值缺少",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if (hr_threshold_max != '' && hr_threshold_min != '' && hr_threshold_max <= hr_threshold_min) {
      wx.showToast({
        title: "湿度阈值不合法",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var taxrate = that.data.taxrate||0;
    if (isNaN(taxrate) == true || Number(taxrate) < 0 || Number(taxrate) > 100){
      wx.showToast({
        title: "税率不合法",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if(!that.data.coord){
      wx.showToast({
        title: "请选择坐标",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    if(!that.data.name){
      wx.showToast({
        title: "请输入名称",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...',
    })
    util.postData("/atapi/warehouse/warehouse/newWarehouse", {
      'CO_ID': app.globalData.CO_ID,
      'name': that.data.name,
      'address': that.data.address,
      'coord': that.data.coord,
      'mark': that.data.mark || '',
      'sub_mark': that.data.sub_mark || '',
      'abbreviation': that.data.mark || '',
      'loading_time': that.data.loading_time,
      'loading_rule': that.data.loading_rule || '',
      'routing_type': that.data.routing_type || '',
      'strategy': that.data.strategy || '',
      'reach_distance_limit': that.data.reach_distance_limit || 0,
      'tp_threshold_max': tp_threshold_max || '',
      'tp_threshold_min': tp_threshold_min || '',
      'hr_threshold_max': hr_threshold_max || '',
      'hr_threshold_min': hr_threshold_min || '',
      'monthly_income':that.data.monthly_income,
      'province': that.data.addressComponent.province,
      'city': that.data.addressComponent.city,
      'area': that.data.addressComponent.area,
      'payment_mode': that.data.payment_mode || '',
      'taxrate':taxrate,
      'customer':that.data.customer||'',
      'project':that.data.project||'',
      'monthly_contract_company':that.data.monthly_contract_company||0,
      'monthly_contract_outer':that.data.monthly_contract_outer||0,
      'is_custom_distance':that.data.is_custom_distance?1:0,
      'price_driver_show':that.data.price_driver_show?1:0,
      'shop_time_fromwh':that.data.shop_time_fromwh?1:0,
      'driver_operation_exception_warn':that.data.driver_operation_exception_warn?1:0,
      'no_vehicle_warn_time':that.data.no_vehicle_warn_time
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
          duration: 3000,
          success: function () {
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/enterprise/warehouse'
              })
            }, 3000);
          }
        });
      } else {
        wx.showToast({
          title:res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          coord: latitude + ',' + longitude,
          address: that.data.address ? that.data.address : res.address,
          name: that.data.name ? that.data.name : res.name
        })
        util.getData("/xypapi/map/routerCalculate/geocode", {
          latitude: res.latitude,
          longitude: res.longitude
        }, function (res, error) {
          console.log(res); console.log(error)
          if (res.data.success) {
            that.setData({
              "addressComponent.province": res.data.component.province,
              "addressComponent.city": res.data.component.city,
              "addressComponent.area": res.data.component.district
            });
          }
        });
      }
    })
  },
  showLocation: function () {
    var that = this;
    var coord = that.data.coord
    if (coord) {
      coord = coord.split(',');
      wx.openLocation({
        latitude: Number(coord[0]),
        longitude: Number(coord[1]),
        scale: 18
      })
    } else {
      wx.showToast({
        title: "请先选择位置",
        image: '/images/wrong.png',
        duration: 3000
      });
    }
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    if (e.currentTarget.dataset.target == 'paymentModeModal') {
      var payment_mode = that.data.payment_mode || app.globalData.payment_mode;
      var _payment_mode = payment_mode.split(",");
      var payment_mode_list = [];
      if (_payment_mode.length > 0) {
        for (var i = 0; i < _payment_mode.length; i++) {
          var _pm = String(_payment_mode[i]).split(":")
          payment_mode_list.push({
            name: _pm[0],
            value: String(_pm[1]).replace('%', '')
          })
        }
      }
      that.setData({
        payment_mode_list: payment_mode_list
      })
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  addPmItem: function () {
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    payment_mode_list.push({ name: '', value: '' });
    that.setData({
      payment_mode_list: payment_mode_list
    })
  },
  deletePmItem: function (e) {
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    var index = e.currentTarget.dataset.index;
    var _payment_mode_list = [];
    for (var i = 0; i < payment_mode_list.length; i++) {
      if (i != index) {
        _payment_mode_list.push(payment_mode_list[i])
      }
    }
    that.setData({
      payment_mode_list: _payment_mode_list
    })
  },
  pminput: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    var payment_mode_list = that.data.payment_mode_list;
    for (var i = 0; i < payment_mode_list.length; i++) {
      if (i == index) {
        if (type == 'name') {
          payment_mode_list[i].name = value;
        }
        if (type == 'value') {
          if (isNaN(value) == false) {
            payment_mode_list[i].value = value;
          } else {
            wx.showToast({
              title: "请输入数字",
              image: '/images/wrong.png',
              duration: 3000
            });
          }
        }
      }
    }
    that.setData({
      payment_mode_list: payment_mode_list
    })
  },
  //保存付款方式
  savePaymentMode: function (e) {
    var that = this;
    var payment_mode_list = that.data.payment_mode_list;
    var _payment_mode = new Array();
    var isPass = true;
    var percentage = 0;
    if (payment_mode_list.length > 0) {
      for (var i = 0; i < payment_mode_list.length; i++) {
        percentage += Number(payment_mode_list[i].value);
        if (payment_mode_list[i].name == '' || payment_mode_list[i].value == '') {
          wx.showToast({
            title: "有空的条目",
            image: '/images/wrong.png',
            duration: 3000
          });
          isPass = false;
          return false;
        }
        _payment_mode[i] = payment_mode_list[i].name + ':' + payment_mode_list[i].value + '%'
      }
      if (percentage != 100) {
        wx.showToast({
          title: "总比率不等100",
          image: '/images/wrong.png',
          duration: 3000
        });
        isPass = false;
        return false;
      }
      that.setData({
        payment_mode: _payment_mode.join(',')
      })
    } else {
      that.setData({
        payment_mode: ''
      })
    }

    if (isPass) {
      that.setData({
        modalName: null
      })
    }
  },
  selectCustomer: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/index/customerList'
    })
  },
  selectProject: function (e) {
    var that = this;
    if(!that.data.customer){
      wx.showToast({
        title: "请先选择客户",
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/index/projectList?customer='+that.data.customer
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'strategy',
      success: function (res) {
        if (res.data) {
          that.setData({
            routing_type: res.data.routing_type,
            strategy: res.data.strategy
          });
          wx.removeStorage({
            key: 'strategy'
          });
        }
      }
    });
     wx.getStorage({
       key: 'path_customer',
       success: function (res) {
         console.log(res)
         if (res.data) {
           that.setData({
             customerName: res.data.name,
             customer:res.data.value
           });
           wx.removeStorage({
             key: 'path_customer',
             success: function (res) {
             }
           });
         }
       }
     });
     wx.getStorage({
      key: 'path_project',
      success: function (res) {
        console.log(res)
        if (res.data) {
          that.setData({
            projectName: res.data.name,
            project:res.data.value
          });
          wx.removeStorage({
            key: 'path_customer',
            success: function (res) {
            }
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})